<?php
//网站主页
class Index extends CI_Controller
{
    private $GetwayWorker;
    private $page_size = 20;

    public function __construct()
    {
        parent::__construct();

        $this->load->model('chat_model','chat_model');

        $this->load->helper("url");

        require_once(APPPATH . 'libraries/GetwayWorker.php');

        $this->GetwayWorker = new GetwayWorker();
    }

    //主页
    public function index()
    {
        //获取当前在线列表
        $lines = $this->GetwayWorker->getAllUidList();

        $list  = [];
        if (!empty($lines))
        {
            $this->load->database();
            $this->db->select('A.id,A.client_id,A.nick_name,A.real_ip,B.url');
            $this->db->from('user_log as A');
            $this->db->join('avatar AS B', 'A.avatar_id = B.id', 'LEFT');
            $this->db->where_in('A.id',$lines);
            $query  = $this->db->get();
            $list   = $query->result_array();

            $this->db->close();

            $now_ip = plum_get_realIP();

            //去掉自己
            foreach ($list as $k => &$v)
            {
                if ($v['real_ip'] == $now_ip)
                {
                    unset($list[$k]);
                }

                $v['url'] = base_url().$v['url'];
            }
        }

        $users['list'] = $list;

        $this->load->view("chat",$users);
    }

    //生成并绑定用户：一个ip一个用户
    public function bindUser()
    {
        $this->load->database();

        $real_ip = $_POST['real_ip'];
        //先查找 根据IP 因为每次刷新设备id都不一致
        $this->db->select('id,nick_name');
        $this->db->where('real_ip',$real_ip);
        $query = $this->db->get('user_log');
        $check = $query->row();

        $address = plum_ip_get_address($real_ip);

        //获取随机头像id
        $this->db->select('id,url');
        $this->db->from('avatar');
        $this->db->order_by('RAND()');
        $this->db->limit(1);
        $query  = $this->db->get();
        $avatar = $query->result_array();

        if (empty($check))
        {
            //新增
            $this->db->trans_start();

            $data = [
                'nick_name'		=> !empty($_POST['nick']) ? mb_substr($_POST['nick'],0,10,'utf-8') : '游客'.rand(11111,99999),
                'avatar_id'		=> $avatar[0]['id'],
                'client_id'		=> $_POST['client_id'],
                'real_ip'       => $real_ip,
                'province'	    => $address['province'],
                'city'			=> $address['city'],
            ];
            $this->db->set('start_time', 'NOW()', FALSE);
            $this->db->insert('user_log', $data);

            $uid = $this->db->insert_id();

            $this->db->trans_complete();

            if ($this->db->trans_status() === FALSE) {
                log_message('error','用户添加失败'.$this->db->_error_message());
                $this->db->close();
                displayJson(400,'服务器链接失败,请稍后重试');
            }

            $nick = $data['nick_name'];
        } else {
            //更新
            $this->db->trans_start();

            $this->db->set('client_id', $_POST['client_id']);
            $this->db->set('avatar_id', $avatar[0]['id']);
            $this->db->set('province', $address['province']);
            $this->db->set('city', $address['city']);
            $this->db->where('id', $check->id);
            $this->db->update('user_log');

            if ($this->db->trans_status() === FALSE) {
                log_message('error','用户更新失败'.$this->db->_error_message().'-id-'.$check->id);
                $this->db->close();
                displayJson(400,'服务器链接失败,请稍后重试');
            }

            $uid  = $check->id;

            $nick = $check->nick_name;
        }

        //获取近7天聊天记录
        $time = date ('Y-m-d', strtotime("-7 day",time()));

        $_POST['page'] = isset($_POST['page']) ? $_POST['page'] : 0;

        $this->db->select('A.uid,A.content,A.create_time,B.nick_name,C.url');
        $this->db->from('content as A');
        $this->db->join('user_log AS B', 'A.uid = B.id', 'LEFT');
        $this->db->join('avatar AS C', 'B.avatar_id = C.id', 'LEFT');
        $this->db->where('A.create_time >=',$time);
        $this->db->where('A.to_uid',0);
        $this->db->order_by('A.id','DESC');

        $offset = $_POST['page'] * $this->page_size;
        $this->db->limit($this->page_size, $offset);

        $query  = $this->db->get();
        $list   = $query->result_array();

        $this->db->close();

        //绑定用户 加入组
        $this->GetwayWorker->bindUid($uid,$_POST['client_id'],'public');

        //处理聊天记录
        if (!empty($list))
        {
            foreach ($list as $key => &$val)
            {
                $val['url'] = base_url().$val['url'];

                if ($val['create_time'] >= date('Y-m-d',time()))
                {
                    $val['create_time'] = date('H:i',strtotime($val['create_time']));
                } else {
                    $val['create_time'] = date('Y-m-d H:i',strtotime($val['create_time']));
                }
            }
        }

        // 向所有人发送(去除当前用户)，表示有新用户连接
        $all = [
            'type'      => 'connect',
            'msg'       => '有新的用户连接',
            'id'        => $uid,
            'nick'      => $nick,
            'avatar'    => base_url().$avatar[0]['url'],
            'ip'        => $real_ip,
        ];
        $this->GetwayWorker->sendToAll(json_encode($all,JSON_UNESCAPED_UNICODE),[$_POST['client_id']]);

        $my = [
            'avatar'  => base_url().$avatar[0]['url'],
            'nick'    => $nick,
            'user_id' => $uid,
            'list'    => $list,
        ];
        displayJson(200,'success',$my);
    }

    //记录用户聊天记录
    public function chatRecord()
    {
        if (
            isset($_POST['content']) && !empty($_POST['content']) &&
            isset($_POST['user_id']) && !empty($_POST['user_id']) &&
            isset($_POST['client_id']) && !empty($_POST['client_id']) &&
            isset($_POST['to_uid'])
        ) {
            $_POST['content'] = trim($_POST['content']);

            if (empty($_POST['content']))
            {
                displayJson(400,'不能发送空白消息');
            }

            if ($_POST['user_id'] == $_POST['to_uid'])
            {
                displayJson(400,'你发信息给自己干嘛？');
            }

            $this->load->database();

            $this->db->select('A.id,A.nick_name,B.url');
            $this->db->from('user_log as A');
            $this->db->join('avatar AS B', 'B.id = A.avatar_id', 'LEFT');
            $this->db->where('A.id',$_POST['user_id']);
            $query = $this->db->get();
            $user  = $query->row();

            $this->db->trans_start();

            $data = [
                'uid'		  => $_POST['user_id'],
                'to_uid'      => $_POST['to_uid'],
                'content'     => htmlspecialchars($_POST['content']),
                'create_time' => date('Y-m-d H:i:s',time())
            ];

            $this->db->insert('content', $data);

            $this->db->trans_complete();

            if ($this->db->trans_status() === FALSE) {
                log_message('error','记录用户聊天失败'.$this->db->_error_message().'-post-'.json_encode($_POST));
                $this->db->close();
                displayJson(400,'服务器繁忙,请稍后重试');
            }

            $this->db->close();

            //向大厅组发送消息--不给当前用户发
            $con = array(
                'type'      => 'text',
                'msg'       => $data['content'],
                'client_id' => $_POST['client_id'],
                'nick'      => $user->nick_name,
                'avatar'    => base_url().$user->url,
                'time'      => date('H:i',time()),
                'from_uid'  => $_POST['user_id'],
                'to_uid'    => $_POST['to_uid'],
            );

            if ($_POST['to_uid'] > 0)
            {
                //向单个用户
                $this->GetwayWorker->sendMessageToUid($_POST['to_uid'],json_encode($con,JSON_UNESCAPED_UNICODE));
            } else {
                //向大厅
                $this->GetwayWorker->sendToGroup('public',json_encode($con,JSON_UNESCAPED_UNICODE),[$_POST['client_id']]);
            }

            $ret = [
                'content' => $data['content'],
                'time'    => date('H:i',time()),
                'avatar'  => base_url().$user->url,
                'nick'    => $user->nick_name,
            ];

            displayJson(200,'发送成功',$ret);
        } else {
            displayJson(400,'数据异常，请稍后重试');
        }
    }

    //获取聊天记录-分页
    public function getPageChatRecord()
    {
        //var_dump($_POST);die;
        if (!isset($_POST['page']) || !is_numeric($_POST['page']))
        {
            displayJson(400,'分页参数丢失');
        }

        $this->load->database();

        //获取近7天聊天记录
        $time = date ('Y-m-d', strtotime("-7 day",time()));

        $this->db->select('A.uid,A.content,A.create_time,B.nick_name,C.url');
        $this->db->from('content as A');
        $this->db->join('user_log AS B', 'A.uid = B.id', 'LEFT');
        $this->db->join('avatar AS C', 'B.avatar_id = C.id', 'LEFT');
        $this->db->where('A.create_time >=',$time);

        if ((int)$_POST['to_uid'] == 0)
        {
            $this->db->where('A.to_uid',$_POST['to_uid']);
        } else {
            //点击的是私人
            $this->db->where_in('A.uid',[$_POST['user_id'],$_POST['to_uid']]);
            $this->db->where_in('A.to_uid',[$_POST['user_id'],$_POST['to_uid']]);
        }

        $this->db->order_by('A.id','DESC');

        $offset = $_POST['page'] * $this->page_size;
        $this->db->limit($this->page_size, $offset);

        $query  = $this->db->get();

        $list   = $query->result_array();

        //处理聊天记录
        if (!empty($list))
        {
            foreach ($list as $key => &$val)
            {
                $val['url'] = base_url().$val['url'];

                if ($val['create_time'] >= date('Y-m-d',time()))
                {
                    $val['create_time'] = date('H:i',strtotime($val['create_time']));
                } else {
                    $val['create_time'] = date('Y-m-d H:i',strtotime($val['create_time']));
                }
            }
        }

        $this->db->close();

        $data['list'] = $list;

        $msg = empty($list) ? '已加载完毕' : '加载成功';

        displayJson(200,$msg,$data);
    }

    //投稿头像
    public function uploadAvatar()
    {
        if (!isset($_POST['uid']) || empty($_POST['uid']) || !isset($_FILES['image']) || empty($_FILES['image']))
        {
            displayJson(400,'上传失败，请刷新后重试');
        }

        $this->chat_model->uploadAvatar();
    }

}
